package com.mixide.ui.part.register;

import com.mixal.hardware.Register;
import com.mixal.software.Byte;
import com.mixal.software.Field;
import com.mixal.software.Word;
import com.mixal.software.Word.Sign;
import com.mixal.software.Words;

import lombok.Getter;

public class RegisterRow {

	private final Register register;
	private Word word;
	
	private @Getter String no;
	private @Getter String sign;
	private @Getter String byte1;
	private @Getter String byte2;
	private @Getter String byte3;
	private @Getter String byte4;
	private @Getter String byte5;
	private @Getter String toChar;
	private @Getter String toInt;

	public RegisterRow(String no, Register register) {
		this.no = no;
		this.register = register;
		this.refresh();
	}
	
	public void setSign(String sign) {
		Word word = null;
		if ("+".equals(sign)) {
			word = new Word(Sign.POSITIVE, this.word.bytes());
		} else {
			word = new Word(Sign.NEGATIVE, this.word.bytes());
		}
		this.changeWord(word);
	}

	public void setByte(int i, String bytei) {
		int bi = Integer.parseInt(bytei, 10);
		Byte[] bytes = this.word.bytes();
		bytes[i - 1] = new Byte(bi);
		Word word = new Word(this.word.sign(), bytes);
		this.changeWord(word);
	}
	
	public void setToChar(String toChar) {
		String str = String.format("%1$5s", toChar);
		Word word = this.word.ofPart(Words.ofFiveChars(str), new Field(1, 5));
		this.changeWord(word);
	}
	
	public void setToInt(String toInt) {
		int num = Integer.parseInt(toInt, 10);
		Word word = new Word(num);
		this.changeWord(word);
	}
	
	private void changeWord(Word word) {
		this.register.store(word);
		this.refresh();
	}
	
	private void refresh() {
		this.word = this.register.content();
		
		this.sign = word.sign().sign();
		
		Byte[] bytes = this.word.bytes();
		this.byte1 = String.format("%02d", bytes[0].toInt());
		this.byte2 = String.format("%02d", bytes[1].toInt());
		this.byte3 = String.format("%02d", bytes[2].toInt());
		this.byte4 = String.format("%02d", bytes[3].toInt());
		this.byte5 = String.format("%02d", bytes[4].toInt());
		this.toChar = Words.toString(this.word);
		this.toInt = String.valueOf(this.word.toInt());
	}
}
